package com.elitel.frame.business.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.service.BaseRepaddonsService;
import com.elitel.frame.base.service.BaseRepconfigService;
import com.elitel.frame.base.service.BaseReptempletService;
import com.elitel.frame.base.service.CfgExtrepService;
import com.elitel.frame.business.service.ExecuteSqlService;
import com.elitel.frame.business.service.SingleReportServerService;
import com.elitel.frame.business.service.SingleTableServerService;
import com.elitel.frame.main.entity.BaseRepaddons;
import com.elitel.frame.main.entity.BaseRepconfig;
import com.elitel.frame.main.entity.BaseReptemplate;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgExtrep;
import com.elitel.frame.main.entity.CfgField;
import com.elitel.frame.main.entity.vo.ReportColumn;

@Controller
@RequestMapping("/business/singleReportServer")
public class SingleReportServerController {
		
	  private static final Logger logger = LoggerFactory.getLogger(SingleReportServerController.class);
	
	  @Autowired
	  private CfgExtrepService cfgExtrepService;
	  @Autowired
	  private BaseRepconfigService baseRepconfigService;
	  @Autowired
	  private BaseReptempletService baseReptempletService;
	  @Autowired
	  private BaseRepaddonsService baseRepaddonsService;
	  @Autowired
	  private RedisCacheComponent redisCacheComponent;
	  @Autowired
	  private ExecuteSqlService executeSqlService;
	  @Autowired
	  private SingleReportServerService singleReportServerService;
	  
	  /**
	   * 
	   * @Title: singleReportShow 
	   * @Description: TODO(单表服务springMVC报表展示接口) 
	   * @author Fanwenquan
	   * @return String
	   * @throws
	   */
	  @RequestMapping(value = "/singleReportShow", method = RequestMethod.GET)
	  public String singleReportShow(Model model, String guid) {
		  BaseReptemplate baseReptemplet = null;
		  List<BaseRepconfig> repConfig = null;
		  List<ReportColumn> columnList = new ArrayList<ReportColumn>();
		  try {
			  //跟据参数查出报表服务的数据源和字段存储关键字
			  CfgExtrep cfgExtrep = cfgExtrepService.selectCfgExtrepByPrimary(guid);
			  //获取数据源  表字段信息
			  Map<String, Object> map = loadDbInformation(cfgExtrep);
			  CfgDb prop = (CfgDb) map.get("datasource");
			  List<CfgField> cfgList = (List<CfgField>) map.get("tableMessage");
			  String str = "select * from " + cfgList.get(0).getDtName();
			  List<Map<String, Object>> list = executeSqlService.executeSql(prop, str);
			  if(null != cfgExtrep) {
				  //查询模板信息
				   baseReptemplet = baseReptempletService.selectBaseRepTemplateByPrimary(cfgExtrep.getTempid());
				  //查询填报信息
				   repConfig = baseRepconfigService.selectRepConfigByRguid(cfgExtrep.getGuid());
				 String columnArray[] = cfgExtrep.getFields().split(",");
				 if(columnArray.length >= 1) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[0])) {
							model.addAttribute("COLUMNTITLE1", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 2) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[1])) {
							model.addAttribute("COLUMNTITLE2", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 3) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[2])) {
							model.addAttribute("COLUMNTITLE3", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 4) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[3])) {
							model.addAttribute("COLUMNTITLE4", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 5) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[4])) {
							model.addAttribute("COLUMNTITLE5", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 6) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[5])) {
							model.addAttribute("COLUMNTITLE6", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 7) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[6])) {
							model.addAttribute("COLUMNTITLE7", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 8) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[7])) {
							model.addAttribute("COLUMNTITLE8", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 9) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[8])) {
							model.addAttribute("COLUMNTITLE9", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 10) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[9])) {
							model.addAttribute("COLUMNTITLE10", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 11) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[10])) {
							model.addAttribute("COLUMNTITLE11", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 if(columnArray.length >= 12) {
					 for (CfgField cfg : cfgList) {
						if(null != cfg.getDfName() && cfg.getDfName().equals(columnArray[11])) {
							model.addAttribute("COLUMNTITLE12", cfg.getDfNameCn());
							break;
						}
					}
				 }
				 for (Map<String, Object> m : list) {
						ReportColumn repColumn= new ReportColumn();
							if(0 < columnArray.length) {
								repColumn.setColunmValue1(m.get(columnArray[0]).toString());
							}
							if(1 < columnArray.length) {
								repColumn.setColunmValue2(m.get(columnArray[1]).toString());
							}
							if(2 < columnArray.length) {
								repColumn.setColunmValue3(m.get(columnArray[2]).toString());
							}
							if(3 < columnArray.length) {
								repColumn.setColunmValue4(m.get(columnArray[3]).toString());
							}
							if(4 < columnArray.length) {
								repColumn.setColunmValue5(m.get(columnArray[4]).toString());
							}
							if(5 < columnArray.length) {
								repColumn.setColunmValue6(m.get(columnArray[5]).toString());
							}
							if(6 < columnArray.length) {
								repColumn.setColunmValue7(m.get(columnArray[6]).toString());
							}
							if(7 < columnArray.length) {
								repColumn.setColunmValue7(m.get(columnArray[7]).toString());
							}
							if(8 < columnArray.length) {
								repColumn.setColunmValue9(m.get(columnArray[8]).toString());
							}
							if(9 < columnArray.length) {
								repColumn.setColunmValue10(m.get(columnArray[9]).toString());
							}
							if(10 < columnArray.length) {
								repColumn.setColunmValue11(m.get(columnArray[10]).toString());
							}
							if(11 < columnArray.length) {
								repColumn.setColunmValue12(m.get(columnArray[11]).toString());
							}
							columnList.add(repColumn);
					}
				 model.addAttribute("RTITLE", cfgExtrep.getRtitle());
			  }
			  // 报表数据源  
		      JRDataSource jrDataSource = new JRBeanCollectionDataSource(columnList);  
		      // 动态指定报表模板url  
		      model.addAttribute("url", baseReptemplet.getTemplateUrl());
		      model.addAttribute("format", "html"); // 报表格式  
		      model.addAttribute("jrMainDataSource", jrDataSource);
		      Map exporterParameters = new HashMap();
		      exporterParameters.put(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD , true);
		      exporterParameters.put(JRHtmlExporterParameter.IMAGES_URI, "../../image?image=");
		      exporterParameters.put(JRHtmlExporterParameter.CHARACTER_ENCODING, "UTF-8");
		      exporterParameters.put(JRExporterParameter.PAGE_INDEX, new Integer(0));
		      model.addAttribute("exporterParameters",exporterParameters);
		      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		      SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
		      for (BaseRepconfig m : repConfig) {
		    	 if(null != m.getRaguid() && !"".equals(m.getRaguid())) {
		    		 BaseRepaddons	br = baseRepaddonsService.selectBaseRepaddonsByKey(m.getRaguid());
		    		 if(br.getPropname().equals("DATE")){
		 				if(m.getPropvalue().equals("@DATE")){
		 					model.addAttribute(br.getPropname(), sdf.format(new Date()));
		 				} else if(m.getPropvalue().equals("@TIME")) {
		 					model.addAttribute(br.getPropname(), sd.format(new Date()));
		 				}
		 				continue;
		 			}
		 			model.addAttribute(br.getPropname(), m.getPropvalue());
		    	 }
				
			}
		  } catch (Exception e) {
			  logger.error(e.getMessage(), e);
		  }
		  
		  return "iReportView";
	  }
	  
	  /**
	   * 
	   * @Title: singleReportToHtml 
	   * @Description: TODO(html形式页面展示(流的方式)) 
	   * @author Fanwenquan
	   * @return String
	   * @throws
	   */
	  @RequestMapping(value = "/singleReportToHtml", method = RequestMethod.GET)
	  public void singleReportToHtml(String guid, String pageIndex, HttpServletRequest request,
	            HttpServletResponse response) {
		  try {
			  singleReportServerService.singleReportToHtml(guid, pageIndex, request, response);
		  } catch (Exception e) {
			  logger.error(e.getMessage(), e);
		  }
	  }
	  
	  /**
	   * 
	   * @Title: singleReportTotalPage 
	   * @Description: TODO(返回报表总页数) 
	   * @author Fanwenquan
	   * @return Object
	   * @throws
	   */
	  @RequestMapping("/singleReportTotalPage")
	  @ResponseBody
	  public Object singleReportTotalPage(String guid, HttpServletRequest request,
	            HttpServletResponse response) {
		Integer returnPage = null;
		try {
			returnPage = singleReportServerService.singleReportTotalPage(guid, request, response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
	    return returnPage;
	  }
	  
	  /**
	   * 
	   * @Title: singleReportToPdf 
	   * @Description: TODO(pdf展示报表) 
	   * @author Fanwenquan
	   * @return void
	   * @throws
	   */
	  @RequestMapping(value = "/singleReportToPdf", method = RequestMethod.GET)
	  public void singleReportToPdf(String guid, HttpServletRequest request,
	            HttpServletResponse response) {
		  try {
			  singleReportServerService.singleReportToPdf(guid, request, response);
		  } catch (Exception e) {
			  logger.error(e.getMessage(), e);
		  }
		  
	  }
	  
	  /**
	   * 
	   * @Title: singleReportExportPdf 
	   * @Description: TODO(pdf导出报表) 
	   * @author Fanwenquan
	   * @return void
	   * @throws
	   */
	  @RequestMapping(value = "/singleReportExportPdf", method = RequestMethod.GET)
	  public void singleReportExportPdf(String guid, String pageIndex, HttpServletRequest request,
	            HttpServletResponse response) {
		  try {
			  singleReportServerService.singleReportExportPdf(guid, pageIndex, request, response);
		  } catch (Exception e) {
			  logger.error(e.getMessage(), e);
		  }
		  
	  }
	  
	  /**
	   * 
	   * @Title: loadDbInformation 
	   * @Description: TODO(加载数据源等基本信息) 
	   * @author Fanwenquan
	   * @return Map<String,Object>
	   * @throws
	   */
	  private Map<String, Object> loadDbInformation(CfgExtrep cfgExtrep){
		    Map<String, Object> map = new HashMap<String, Object>();
			if(null != cfgExtrep) {
				//查询表名,表字段信息
				List<CfgField> cfgList = redisCacheComponent.cfgFieldRedisCache(cfgExtrep.getDtConfigId());
			    //查询及数据源标识
			    CfgDb prop = redisCacheComponent.cfgDBRedisCache(cfgExtrep.getDtDbKey());
				map.put("tableMessage", cfgList);
				map.put("datasource", prop);
			}
		  return map;
	  }
	  
}
